<script setup lang="ts">
import Motion from "@/components/motion/motion";
import { useRenderIcon } from "@/components/icon/src/hooks";
import { ref, reactive } from "vue";
import { FormInstance, FormRules } from "element-plus";
import { LoginParams } from "@/core/api/api.interface";
import { passWordRule } from "@/components/sf";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { LoginExposeOption } from "@/views/interface";
import { toRaw } from "vue";
const loginForm = reactive<LoginParams>({
  username: "",
  password: "",
  grant_type: "password",
  refresh: false
});
const formRef = ref<FormInstance>();
const formSchema = [
  {
    rules: [
      {
        required: true,
        message: "请输入账号",
        trigger: "blur"
      }
    ],
    showPassWord: false,
    placeholder: "账号",
    icon: User,
    delay: 100,
    clearable: true,
    key: "username"
  },
  {
    showPassWord: true,
    placeholder: "密码",
    icon: Lock,
    delay: 150,
    clearable: true,
    key: "password"
  }
];
const loginRules = reactive({
  password: [passWordRule]
} as FormRules);

const validateData = async () => {
  return new Promise<LoginParams>(res => {
    if (!formRef.value) {
      res(null);
    } else {
      formRef?.value.validate((valid, _) => {
        res(valid ? toRaw(loginForm) : null);
      });
    }
  });
};
defineExpose<LoginExposeOption>({
  validateData
});
</script>
<template>
  <el-form ref="formRef" :model="loginForm" :rules="loginRules" size="large">
    <template v-for="schema in formSchema" :key="schema.key">
      <Motion :delay="schema.delay">
        <el-form-item :rules="schema.rules || []" :prop="schema.key">
          <el-input
            :clearable="schema.clearable"
            v-model="loginForm[schema.key]"
            :placeholder="schema.placeholder"
            :show-password="schema.showPassWord"
            :prefix-icon="useRenderIcon(schema.icon)"
          />
        </el-form-item>
      </Motion>
    </template>
  </el-form>
</template>
